#==================================================
#	Attack
#==================================================
#  攻击
#==================================================
# @datetime: 2021-12-27 23:46:23
#==================================================

extends "res://addons/function_tree/src/base/function/statemachineroot/State.gd"


var play_anim

var duration_timer = Timer.new()
# 变招计数
var change_attack = ChangeAttackCounter.new(self)



#==================================================
#   内部方法
#==================================================
func _enter_tree():
	duration_timer.one_shot = true
	duration_timer.autostart = false
	if duration_timer.connect("timeout", self, "action_finish") != OK:
		print_debug(name, "连接时出现错误")
	add_child(duration_timer)



#==================================================
#   自定义方法
#==================================================
#(override)
func _init_node():
	._init_node()
	play_anim = get_function("PlayAnim")



#==================================================
#   状态方法
#==================================================
#(override)
func enter(data):
	var action_name = data.action_name
	if action_name == GCK.Anim.Attack:
		change_attack.start(0.8)
		
		if change_attack.next() <= 4:
			# 随机获取一个
			action_name = rand_list([
				GCK.Anim.Attack01, 
				GCK.Anim.Attack02,
			])
		
		# 连续攻击4次，则播放拔剑攻击
		else:
			change_attack.stop()
			action_name = GCK.Anim.DrawSword
		
		# 设置播放的动画
		play_anim.play(action_name)
		get_function("Attack").control(null)
		# 攻击时向前的小移动
		get_function("Sprint").control(property.face_dir + host.global_position)
		
	elif action_name == GCK.Anim.Kick:
		# 播放动画
		play_anim.play(action_name)
		# 执行动作
		get_function("Kick").control(data)
	
	# 设置持续时间
	var time = play_anim.get_anim_length(action_name)
	duration_timer.start(time)


#(override)
func exit():
	duration_timer.stop()


##  动作完成
func action_finish():
	switch_to("Normal")


##  随机获取 list 中的一个
## @list  
func rand_list(list: Array):
	return list[randi() % list.size()]



#==================================================
#   变招计数器
#==================================================
class ChangeAttackCounter:
	var attack_count : int = 0
	var change_attack_timer : Timer = Timer.new()
	
	func _init(host: Node):
		change_attack_timer.one_shot = true
		change_attack_timer.autostart = false
		if change_attack_timer.connect("timeout", self, "stop") != OK:
			print_debug("连接出现问题")
		if not host.is_inside_tree():
			yield(host, "tree_entered")
		host.add_child(change_attack_timer)
	
	func get_count() -> int:
		return attack_count
	
	func next() -> int:
		attack_count += 1
		return attack_count
	
	func start(time: float = INF):
		if time == INF:
			time = 1.0	# 默认 1.0
		change_attack_timer.start(time)
	
	func stop():
		# 重置 
		change_attack_timer.stop()
		attack_count = 0
	

